import {ref, onMounted} from "vue";
import type {IApiResponseList, IQueryParams} from "@/types";


interface IConfig<T, P = Record<string, any>> {
    api: (params: P) => Promise<IApiResponseList<T>>;
    immediate?: boolean;
}


const mergeParams = <P>(defaultParams: IQueryParams, searchParams: P) => {
    return {...defaultParams, ...searchParams};
}


export function useTableHook<T, P = Record<string, any>>(config: IConfig<T, P>) {
    const {api, immediate} = config;
    const defaultParams = ref<IQueryParams>({
        page: 1,
        page_size: 10
    });
    const rowKey = (record: Record<string, any>) => record.id;
    const loading = ref<boolean>(false);
    const dataSource = ref<T[]>([]);
    const pagination = ref({
        page: 1,
        page_size: 10,
        count: 0
    })


    /**
     * 获取数据
     * @param searchParams
     */
    const handleGetList = async (searchParams: P = {} as P) => {
        try {
            loading.value = true;
            const params = mergeParams(defaultParams.value, searchParams);
            const response = await api(params);
            dataSource.value = response.data.records;
            pagination.value.count = response.data.count;
        } catch (error) {
            console.log("handleGetList Error", error);
        } finally {
            loading.value = false;
        }
    }


    /**
     * 查询功能
     * @param params
     */
    const handleSearch = async (params: P) => {
        defaultParams.value = {
            page: 1,
            page_size: 10
        };
        await handleGetList(params);
    }


    /**
     * 重置功能
     */
    const handleReset = async () => {
        await handleGetList();
    }


    /**
     * 切换页码
     * @param page
     */
    const handlePageChange = async (page: number) => {
        defaultParams.value.page = page;
        await handleGetList();
    }


    /**
     * 切换条数
     * @param pageSize
     */
    const handlePageSizeChange = async (pageSize: number) => {
        defaultParams.value.page_size = pageSize;
        await handleGetList();
    }


    onMounted(() => {
        immediate && handleGetList();
    })


    return {
        rowKey,
        loading,
        dataSource,
        pagination,
        handleSearch,
        handleReset,
        handlePageChange,
        handlePageSizeChange
    }
}
